#include "huffman.h"
#include "simbolo.h"

#include <QString>
#include <QtDebug>
#include <QHash>
#include <QChar>
#include <QList>

void Huffman::compress(const QString& riga) {
	QHash<QChar, int>* ch = calcolaOccorrenze(riga);
	qDebug() << *ch;
	QList<Simbolo>* sch = costruisciArray(*ch);
	
	QString str("");
	Simbolo *s;
	foreach (*s, *sch)
		str += s->toString();
	qDebug() << str;
}

QHash<QChar, int>* Huffman::calcolaOccorrenze(const QString& riga) {
	QHash<QChar, int>* hm = new QHash<QChar, int>();
	for (int i = 0; i < riga.length(); i++) {
		if (hm->value(riga.at(i)) == 0)
			hm->insert(riga.at(i),1);
		else
			hm->insert(riga.at(i), hm->value(riga.at(i)) + 1);
	}
	return hm;
}

QList<Simbolo>* Huffman::costruisciArray(const QHash<QChar, int>& hash) {
	QList<Simbolo>* list = new QList<Simbolo>();
	QList<QChar> keys = hash.keys();
	QChar k;
	foreach (k,keys)
		list->append(Simbolo(k,hash.value(k)));
	Simbolo *s;
	QString str("");
	foreach (*s, *list)
		str += s->toString();
	qDebug() << str;
	qSort(list->begin(), list->end());
	return list;
}
